package com.dgut.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.ConcurrentHashMap;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(NotLoginException.class)
    public Object handlerNotLoginException(NotLoginException nle, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ConcurrentHashMap resultMap = new ConcurrentHashMap();
        nle.printStackTrace();

        String message = "";
        if(nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未登录";
        }
        else if(nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "登录失效";
        }
        else if(nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "登录过期";
        }
        else if(nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "已被顶下线";
        }
        else if(nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "已被踢下线";
        }
        else {
            message = "未登录";
        }
        resultMap.put("error",message);
        return resultMap;
    }

    @ExceptionHandler(NotRoleException.class)
    public Object handlerNotRoleException(NotRoleException nre, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ConcurrentHashMap resultMap = new ConcurrentHashMap();
        nre.printStackTrace();
        resultMap.put("error",nre.getRole());
        return resultMap;
    }
}
